package com.forte.fortePoiUtils.merger.XSSF;

import com.forte.fortePoiUtils.merger.ExcelMerger;
import com.forte.fortePoiUtils.typeEnum.ExcelType;
import com.forte.utils.stream.ExStream;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.stream.Stream;

/**
 * xssf类型的合并输出
 *
 * @author ForteScarlet <[email]ForteScarlet@163.com>
 * @since JDK1.8
 **/
public class XSSFExcelMerger extends ExcelMerger {

    private static ExcelType TYPE = ExcelType.XSSF;

    public XSSFExcelMerger(OutputStream out) {
        super(out);
    }

    public XSSFExcelMerger(File out) throws FileNotFoundException {
        super(out);
    }


    @Override
    public void merger() throws IOException {
        // 获取表流
        Stream<Sheet> sheets = getSheets();
        // 获取工作簿
        Workbook workbook = TYPE.getWorkbook();

        // 遍历sheet
        sheets.forEach(s -> {
            //创建sheet表格
            Sheet sheet = workbook.createSheet(s.getSheetName());
            //遍历拷贝的row
            ExStream.byIter(s.rowIterator()).forEach(r -> {
                //创建行
                Row row = sheet.createRow(r.getRowNum());
                row.setHeight(r.getHeight());
                row.setHeightInPoints(r.getHeightInPoints());
                row.setZeroHeight(r.getZeroHeight());

                //遍历拷贝的单元格
                ExStream.byIter(r.cellIterator()).forEach(c -> {
                    //创建单元格
                    Cell cell = row.createCell(c.getColumnIndex());
                    //拷贝部分数据
                    cell.setCellType(c.getCellType());
                    cell.setCellValue(c.getStringCellValue());
                    cell.setCellComment(c.getCellComment());
                });
            });
        });


        //遍历结束，输出
        try (OutputStream out = getOut()) {
            workbook.write(out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
